import 'package:film/controller/auth_controller.dart';
import 'package:film/controller/film_all_controlle.dart';
import 'package:film/model/film_category_model.dart';
import 'package:film/model/film_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class FilmAllScreen extends StatelessWidget {
  FilmAllScreen({Key? key}) : super(key: key);
  final AuthController authController = Get.find();
  final FilmAllController filmCategoryController = Get.find();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('全部'),
        centerTitle: true,
        elevation: 0,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.lightBlue.shade300, Colors.lightBlue.shade600],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
        ),
      ),
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: _buildFilterArea(),
          ),
          Obx(
            () => filmCategoryController.filmList.isEmpty
                ? SliverFillRemaining(
                    child: const Center(child: Text('没有找到相关影片')),
                  )
                : _buildFilmGridSliver(),
          ),
        ],
      ),
    );
  }

  /// 筛选区域
  Widget _buildFilterArea() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
      child: Column(
        children: filmCategoryController.filterCategories.map((category) {
          return _buildFilterRow(category);
        }).toList(),
      ),
    );
  }

  /// 筛选区域item
  Widget _buildFilterRow(FilterCategory category) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6.0),
      child: Row(
        children: [
          if (category.options.contains('全部'))
            Obx(
              () => _buildFilterChip(
                categoryKey: category.key,
                option: '全部',
                isSpecial: true,
                isSelected: filmCategoryController.selectedFilters[category.key] == '全部',
              ),
            ),
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              physics: const BouncingScrollPhysics(),
              child: Row(
                children: category.options.where((option) => option != '全部').map((option) {
                  return Padding(
                    padding: const EdgeInsets.only(left: 16.0),
                    child: Obx(
                      () => _buildFilterChip(
                        categoryKey: category.key,
                        option: option,
                        isSelected: filmCategoryController.selectedFilters[category.key] == option,
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 筛选标签
  Widget _buildFilterChip({
    required String categoryKey,
    required String option,
    required bool isSelected,
    bool isSpecial = false,
  }) {
    return GestureDetector(
      onTap: () => filmCategoryController.selectFilterOption(categoryKey, option),
      child: isSpecial
          ? Container(
              padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
              decoration: BoxDecoration(
                color: isSelected ? Colors.red.withOpacity(0.1) : const Color(0xFFF5F5F5),
                borderRadius: BorderRadius.circular(8.0),
              ),
              child: Text(
                option,
                style: TextStyle(
                  fontSize: 15,
                  color: isSelected ? Colors.red : Colors.black87,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            )
          : Container(
              padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
              child: Text(
                option,
                style: TextStyle(
                  fontSize: 15,
                  color: isSelected ? Colors.red : Colors.black87,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            ),
    );
  }

  /// 影片列表
  Widget _buildFilmGridSliver() {
    return Obx(
      () => SliverPadding(
        padding: const EdgeInsets.all(12.0),
        sliver: SliverGrid(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 12.0,
            mainAxisSpacing: 12.0,
            childAspectRatio: 2 / 3.5,
          ),
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              final film = filmCategoryController.filmList[index];
              return _buildFilmCard(film);
            },
            childCount: filmCategoryController.filmList.length,
          ),
        ),
      ),
    );
  }

  /// 单个影片
  Widget _buildFilmCard(Film film) {
    return GestureDetector(
      onTap: () => authController.checkToken('/film', arguments: {'vodId': film.vodId}),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: Stack(
                fit: StackFit.expand,
                children: [
                  Image.network(
                    film.vodPic ?? '',
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, progress) => progress == null ? child : const Center(child: CircularProgressIndicator(strokeWidth: 2.0)),
                    errorBuilder: (context, error, stack) => const Icon(Icons.broken_image, color: Colors.grey),
                  ),
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.bottomCenter,
                          end: Alignment.topCenter,
                          colors: [Colors.black.withOpacity(0.7), Colors.transparent],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 6),
          Text(
            film.vodName ?? '',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }
}
